import json
import re
import random

from django.contrib.auth import authenticate, login
from django.http import JsonResponse
from django.views import View
from qiniu import put_data
from ronglian_sms_sdk import SmsSDK

# 判断用户名是否重复
from users.models import User


#  users.views.py


#  3. views.py
from utils.is_login import LoginRequiredJSONMixin

def upload_image(request):

    # 1. 接收外界传入的参数 文件对象
    data_file = request.FILES.get('head_img')



    from qiniu import Auth, put_file

    # 需要填写你的 Access Key 和 Secret Key
    access_key = 'a7SajxShVdc_DTDOWwZ6KjFFe8UyXkcIVijFqdNa'
    secret_key = 'mgwyrszkzqpDB_dEpacg-v5AB8MzOByAYK-SROh-'

    # 构建鉴权对象
    q = Auth(access_key, secret_key)

    # 要上传的空间
    bucket_name = '2312a'

    # 生成上传 Token，可以指定过期时间等
    token = q.upload_token(bucket_name)

    # 上传图片 二进制流
    ret, info = put_data(token,None, data_file.read())

    print(info)
    print(ret)

    #  将 文件路径 存储在mysql 数据库
    user = User.objects.get(username='laowang')
    user.photo = f"/{ret['hash']}"
    user.save()


    return JsonResponse({'msg':'上传成功！'})


class UpdatePWDView(LoginRequiredJSONMixin,View):
    def put(self, request):
        # 2.1 接收参数--请求体--POST--body
        json_dict =json.loads(request.body)
        old_pwd = json_dict.get('old_password')
        new_password = json_dict.get('new_password')
        new_password2 = json_dict.get('new_password2')

        # 2.2 校验参数--判空-判断正则
        if new_password2 != new_password:
            return JsonResponse({'status':400, 'errmsg':'两次密码不一致'})

        # 2.3 校验原始密码--密码加密问题-check_password()
        verify_result = request.user.check_password(old_pwd)
        if verify_result:
            # 2.4 修改密码--set_password()
            request.user.set_password(new_password)
        else:
            return JsonResponse({'status': 400, 'errmsg': '原始密码不正确'})

        request.user.save()

        # 2.5 return
        return JsonResponse({'code':0})

class InfoView(LoginRequiredJSONMixin,View):
    def get(self, request):
       

        data_dict = {
           'username':request.user.username,
            'mobile':request.user.mobile,
            'email':request.user.email,
            'email_active':True
        }

        return JsonResponse({'code':0, 'info_data':data_dict})

class LoginView(View):

    def post(self, request):
        # 1.接收
        data_dict = json.loads(request.body)
        username = data_dict['username']
        password = data_dict['password']
        remembered = data_dict['remembered']
        # 2.校验

        # 3.主逻辑
        user = authenticate(username=username, password=password)
        if not user:
            return JsonResponse({'code': 400})

        # 保持登录状态
        login(request, user)

        # 判断是否要记住登录
        if remembered:
            # 记住
            pass
        else:
            # 不记住
            request.session.set_expiry(0)

        # 4.返回
        return JsonResponse({'code': 0, 'errmsg': '登录成功！'})


class SmsCodeView(View):
    def get(self, request, mobile):
        from django_redis import get_redis_connection
        #  2.连接redis
        redis_client = get_redis_connection('default')

        sdk = SmsSDK('8aaf0708697b6beb01699f54fc6317eb', '8aaf0708697b6beb01699f54fc63123',
                     '8aaf0708697b6beb01699f54fc6317eb')
        # 短信验证码的值
        sms_code = random.randint(1000, 9999)
        print(sms_code)

        # 1.获取 是否发送短信的 标志
        send_flag = redis_client.get(f'flag_{mobile}')

        # 2.判断是否有值
        if send_flag:
            return JsonResponse({'code': 400, 'errmsg': '短信发送太频繁了'})

        result = sdk.sendMessage('1', mobile, datas=(sms_code, 5))

        reuslt_dict = json.loads(result)
        if reuslt_dict['statusCode'] != '000000':
            print('发送短信失败！')

        # 发送了就保存
        #  1.导包

        #  3. set(mobile,'12344', 300)
        # 实例化管道对象
        p1 = redis_client.pipeline()

        # 给管道添加任务
        p1.set(mobile, sms_code, 300)
        p1.set(f'flag_{mobile}', 1, 60)
        # 执行操作
        p1.execute()

        return JsonResponse({'code': 0})


class RegisterView(View):
    def post(self, request):
        # 1.接收参数
        json_dict = json.loads(request.body)
        username = json_dict.get('username')
        password = json_dict.get('password')
        password2 = json_dict.get('password2')
        mobile = json_dict.get('mobile')
        sms_code = json_dict.get('sms_code')

        allow = json_dict.get('allow', False)

        # 2.校验参数
        # 2.1 判空
        if not all([username, password, password2, mobile, sms_code]):
            return JsonResponse({'code': 400, 'msg': '参数不能空！'})

        # 2.2 判断正则
        # 用户名
        if not re.match('^[a-zA-Z0-9_-]{5,20}$', username):
            return JsonResponse({'code': 400, 'msg': '用户名格式不正确！'})
        if username.isdigit():
            return JsonResponse({'code': 400, 'msg': '用户名不能是纯数字！'})
        # 密码
        if not re.match('^\w{8,20}$', password):
            return JsonResponse({'code': 400, 'msg': '密码格式不正确！'})

        # 判断两次密码是否一致
        if password != password2:
            return JsonResponse({'code': 400, 'msg': '两次密码是否一致！'})

        # 手机号
        if not re.match('^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400, 'msg': '手机号格式不正确！'})

        # 短信验证码 6位--纯数字
        if not (sms_code.isdigit() and len(sms_code) == 4):
            return JsonResponse({'code': 400, 'errmsg': '短信验证码不正确！'})

        # 2.3 判断 是否勾选了协议
        if not allow:
            return JsonResponse({'code': 400, 'msg': '必须同意协议！'})

        from django_redis import get_redis_connection
        redis_client = get_redis_connection()
        back_end_sms_code = redis_client.get(mobile)

        if sms_code.encode() != back_end_sms_code:
            return JsonResponse({'code': 400, 'errmsg': '短信验证码无效'})

        # 3.核心共-增加-create--create_user
        User.objects.create_user(username=username, password=password, mobile=mobile)

        # 4.返回
        return JsonResponse({'code': 0, 'errmsg': '注册成功！'})


class MobileView(View):

    def get(self, request, mobile):
        result = {'code': 400, 'errmsg': '交互成功！', 'count': 0}

        # 1.接收参数 -mobile
        # 2.校验参数

        # 3.核心逻辑--去数据查看一下这个人有没有 -count()
        count = User.objects.filter(mobile=mobile).count()

        # 4.返回
        result['code'] = 0
        result['count'] = count
        res = JsonResponse(result)
        return res


class UserNameView(View):

    def get(self, request, username):
        result = {'code': 400, 'errmsg': '交互成功！', 'count': 0}

        # 1.接收参数 -username
        # 2.校验参数
        if username.isdigit():
            res = JsonResponse(result)
            return res

        # 3.核心逻辑--去数据查看一下这个人有没有 -count()
        count = User.objects.filter(username=username).count()

        # 4.返回
        result['code'] = 0
        result['count'] = count
        res = JsonResponse(result)
        return res
